package task5.chat;

import task5.Util;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;

/**
 * 客户端从服务器接收类
 */
public class ClientReceive implements Runnable{
    // 定义输入流
    private DataInputStream dataInputStream;
    // 判断线程是否正在运行
    private boolean isRunning = true;

    public ClientReceive(Socket socket) {
        try {
            dataInputStream = new DataInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            // 若客户端出现异常，则关闭
            isRunning = false;
            Util.close(dataInputStream);
        }
    }

    /**
     * 从服务器接收消息
     * @return
     */
    public String receive(){
        String message = "";
        try {
            message = dataInputStream.readUTF();
        } catch (IOException e) {
            e.printStackTrace();
            // 若客户端出现异常，则关闭
            isRunning = false;
            Util.close(dataInputStream);
        }
        return message;
    }
    @Override
    public void run() {
        while (isRunning){
            System.out.println(receive());
        }
    }
}
